﻿using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using ZenSystemService.Api.Services;

namespace ZenSystemService.Api.Common.Auth
{
    public class FunctionAuthorizationHandler : AuthorizationHandler<FunctionRequirement>
    {
        private readonly AuthService _authService;

        public FunctionAuthorizationHandler(AuthService authService)
        {
            _authService = authService;
        }

        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, FunctionRequirement requirement)
        {
            if (context.User == null || !context.User.Identity.IsAuthenticated)
            {
                context.Fail();
                return;
            }

            var userName = context.User.Identity.Name;

            var hasAccess = await _authService.UserHasAccessToFunctionAsync(userName, requirement.FunctionName);

            if (hasAccess)
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }
        }
    }
}